import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import '../../resources/kq_theme_colors.dart';

import '../../config/kq_global.dart';
import '../../resources/kq_images.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import '../textFiled/kq_textfiled.dart';
import 'entity/kq_form_entity.dart';

class KqMoreAutoView extends StatefulWidget {
  const KqMoreAutoView({
    Key? key,
    required this.data,
    this.min = 1,
    this.didSelect,
  }) : super(key: key);
  final KqFormEntity data; //extraData:[KqFormSubEntity]
  final int min;
  final Function(KqFormSubEntity entity)? didSelect;

  @override
  State<KqMoreAutoView> createState() => KqMoreAutoViewState();
}

class KqMoreAutoViewState extends State<KqMoreAutoView> {
  @override
  void initState() {
    widget.data.widgetState = this;
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }


  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY =
          scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }


  //每一项点击
  void handleTap(KqFormSubEntity entity) {
    if (widget.didSelect != null) {
      widget.didSelect!(entity);
    }
  }

  //增加
  void handleAdd() {
    setState(() {
      List source = widget.data.extraData ?? [];
      source.add(KqFormSubEntity(
          title: '', titleId: '', value: widget.min.toString()));
      widget.data.extraData = source;
    });
  }

  //加减
  Widget renderCount(KqFormSubEntity item, int index) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      mainAxisSize: MainAxisSize.min,
      children: [
        InkWell(
          onTap: () {
            setState(() {
              String value = item.value != '' && item.value != null
                  ? item.value!
                  : widget.min.toString();
              int count = int.parse(value);
              if (count <= widget.min) {
                if (item.value != '' || item.value != null) {
                  setState(() {
                    item.value = widget.min.toString();
                  });
                }
                return;
              }
              count = count - 1;
              item.value = count.toString();
            });
          },
          child: Image.asset(
            int.parse(item.value != '' && item.value != null
                        ? item.value!
                        : widget.min.toString()) <=
                    widget.min
                ? KqImages.commonIcReduceDisabled
                : KqImages.commonIcReduceNormal,
            width: 32.r,
            height: 26.r,
            package: KqGlobal.packageName,
          ),
        ),
        SizedBox(
            width: widget.data.showUnit ? 50.r : 60.r,
            child: KqTextFiled(
              maxLines: 1,
              inputType: TextInputType.number,
              enableClearButton: false,
              fontSize: KqThemeManager.instance
                      .getConfig()
                      .formConfig
                      .contentFontSize ??
                  16.sp,
              newValue: item.value ?? '',
              textAlign: TextAlign.center,
              textAlignVertical: TextAlignVertical.center,
              inputFormatters: [FilteringTextInputFormatter.digitsOnly],
              onChanged: (txt) {
                setState(() {
                  item.value = txt;
                });
              },
            )),
        InkWell(
          onTap: () {
            setState(() {
              String value = item.value != '' && item.value != null
                  ? item.value!
                  : widget.min.toString();
              int count = int.parse(value);
              count = count + 1;
              item.value = count.toString();
            });
          },
          child: Image.asset(
            KqImages.commonIcIncreaseNormal,
            width: 32.r,
            height: 26.r,
            package: KqGlobal.packageName,
          ),
        )
      ],
    );
  }

  Widget renderDelete(int index) {
    return widget.data.extraData != null && widget.data.extraData.length > 1
        ? InkWell(
            onTap: () {
              //删除
              setState(() {
                List source = widget.data.extraData;
                if (source.length > index) {
                  source.removeAt(index);
                }
              });
            },
            child: Container(
              color: KqThemeColors.bgTransparent,
              width: 34.r,
              height: 44.r,
              child: Image.asset(
                KqImages.commonIcDelete16Red,
                width: 16.r,
                height: 16.r,
                package: KqGlobal.packageName,
              ),
            ),
          )
        : Container(
            width: 34.r,
            height: 44.r,
            color: KqThemeColors.bgTransparent,
          );
  }

  Widget renderCell(KqFormSubEntity item, int index) {
    String title = widget.data.hint ?? '';
    if (item.title != null && item.title != '') {
      title = item.title!;
    }
    return Column(
      children: [
        Row(
          children: [
            renderDelete(index),
            Expanded(
                child: Container(
              margin: EdgeInsets.only(right: 20.r),
              color: KqThemeColors.bgTransparent,
              height: 44.r,
              child: InkWell(
                onTap: () {
                  handleTap(item);
                },
                child: Row(
                  children: [
                    Expanded(
                        child: Text(
                      title,
                      style: TextStyle(
                          color: item.title != null && item.title != ''
                              ? KqThemeColors.text26
                              : KqThemeColors.textBF,
                          fontSize: KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .contentFontSize ??
                              16.sp),
                    )),
                    Image.asset(
                      KqImages.commonIcZhankai16Grey,
                      width: 16.r,
                      height: 16.r,
                      package: KqGlobal.packageName,
                    )
                  ],
                ),
              ),
            )),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.r),
              child: renderCount(item, index),
            ),
            Visibility(
                visible: widget.data.showUnit,
                child: Container(
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(right: 16.r),
                  width: 45.r,
                  child: Text(
                    item.unit ?? '',
                    maxLines: 1,
                    style: TextStyle(
                        fontSize: KqThemeManager.instance
                                .getConfig()
                                .formConfig
                                .unitFontSize ??
                            14.sp,
                        color: KqThemeColors.text59),
                  ),
                ))
          ],
        ),
        Visibility(visible: !widget.data.hideDivider, child: const KqDivider())
      ],
    );
  }

  List<Widget> renderList() {
    List source = widget.data.extraData ?? [];
    List<Widget> listView = [];
    for (var i = 0; i < source.length; i++) {
      KqFormSubEntity item = source[i];
      listView.add(renderCell(item, i));
    }
    return listView;
  }

  //左侧的必填
  Widget renderStarView() {
    var star = widget.data.mustInput ? '∗' : '';
    return SizedBox(
      width: 16.r,
      child: Text(
        star,
        textAlign: TextAlign.center,
        style: TextStyle(
            color: KqThemeColors.textRed,
            fontSize: KqThemeManager.instance
                    .getConfig()
                    .formConfig
                    .mustInputFontSize ??
                16.sp),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.data.widgetState = this;
    return SingleChildScrollView(
      child: Column(
        children: [
          Container(
            color: Colors.white,
            child: Row(
              children: [
                Expanded(
                    child: Row(
                  children: [
                    renderStarView(),
                    Flexible(
                        child: Text(
                      widget.data.title,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: widget.data.titleColor ?? KqThemeColors.text26,
                          fontSize: KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .titleFontSize ??
                              16.sp),
                    )),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 5.r),
                      child: Text(
                        "第${widget.data.extraData != null ? widget.data.extraData!.length : '0'}条",
                        maxLines: 1,
                        style: TextStyle(
                            color: widget.data.contentColor ?? KqThemeColors.text59,
                            fontSize: KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .mustInputFontSize ??
                                14.sp),
                      ),
                    ),
                  ],
                )),
                InkWell(
                  onTap: () {
                    handleAdd();
                  },
                  child: Container(
                      alignment: Alignment.centerRight,
                      height: 44.r,
                      padding: EdgeInsets.symmetric(horizontal: 16.r),
                      child: Image.asset(
                        KqImages.commonIcXinzeng16Blue,
                        width: 16.r,
                        height: 16.r,
                        package: KqGlobal.packageName,
                      )),
                )
              ],
            ),
          ),
          Container(
              color: KqThemeColors.bgF4,
              child: ListView(
                padding: const EdgeInsets.all(0),
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                children: renderList(),
              ))
        ],
      ),
    );
  }
}
